import { defineStore } from 'pinia';
import userApi from '/shop/api/user';
import $share from '/shop/platform/share';
import { isEmpty, cloneDeep, clone } from 'lodash';
import cart from './cart';
import app from './app';
import { showAuthModal } from '/shop/hooks/useModal';
import { ref, reactive } from 'vue';

// 默认用户信息
const defaultUserInfo = {
	avatar: '', // 头像
	nickname: '', // 昵称
	gender: 0, // 性别
	mobile: '', // 手机号
	money: '--', // 余额
	commission: '--', // 佣金
	score: '--', // 积分
	verification: {}, // 认证字段
	id: '',
	username: '',
};

// 默认订单、优惠券等其他资产信息
const defaultNumData = {
	coupons_num: '--',
	order_num: {
		aftersale: 0,
		nocomment: 0,
		noget: 0,
		nosend: 0,
		unpaid: 0,
	},
};

const user = defineStore(
	'user',
	() => {
		// let userInfo = reactive(clone(defaultUserInfo));
		let userInfo = ref(clone(defaultUserInfo));
		let isLogin = ref(!!uni.getStorageSync('token'));
		let numData = reactive(cloneDeep(defaultNumData)); // 用户数据
		let lastUpdateTime = ref(0); // 上次更新时间

		let getInfo = async () => {
			//  vue pinia 组合模式 不支持reactive
			const { code, data } = await userApi.profile();
			console.log('getInfo: ', data);
			if (code !== '0') return;
			userInfo.value = data;
			console.log('userInfo: ', userInfo);
			return Promise.resolve(data);
		};

		let getNumData = async () => {
			// const { code, data } = await userApi.data();
			// if (code === '0') {
			// 	numData = data;
			// }
		};

		let addShareLog = async (params) => {
			const { code } = await userApi.addShareLog(params);
			if (code === '0') uni.removeStorageSync('shareLog');
		};

		let clearLogin = () => {
			isLogin.value = false;
		};

		let setToken = (token = '') => {
			if (token === '') {
				isLogin.value = false;
				uni.removeStorageSync('token');
			} else {
				isLogin.value = true;
				uni.setStorageSync('token', token);
				loginAfter();
			}
			return isLogin.value;
		};

		let updateUserData = async () => {
			if (!isLogin.value) {
				resetUserData();
				return;
			}
			const nowTime = new Date().getTime();
			if (lastUpdateTime.value + 5000 > nowTime) return;
			console.log('updateUserData====: ');
			await getInfo();
			getNumData();
			lastUpdateTime.value = nowTime;
			return userInfo;
		};

		let resetUserData = () => {
			setToken();
			userInfo = clone(defaultUserInfo);
			numData = cloneDeep(defaultNumData);
			cart().emptyList();
		};

		let loginAfter = async () => {
			await updateUserData();
			cart().getList();
			// 登录后设置全局分享参数
			$share.getShareInfo();
			// 提醒绑定手机号
			console.log('绑定手机号start');
			console.log('app().platform: ', app().platform);
			console.log('!userInfo.verification?.mobile: ', !userInfo.verification?.mobile);
			let b = app().platform.bind_mobile && !userInfo.verification?.mobile;
			console.log('bbb: ', b);
			if (app().platform.bind_mobile && !userInfo.verification?.mobile) {
				console.log('绑定手机号start--end');
				showAuthModal('changeMobile');
			}

			// 添加分享记录
			const shareLog = uni.getStorageSync('shareLog');
			if (!isEmpty(shareLog)) {
				addShareLog({
					...shareLog,
				});
			}
		};

		let logout = async (force = false) => {
			if (!force) {
				const { code } = await userApi.logout();
				if (code === '0') {
					resetUserData();
				}
			}
			if (force) {
				resetUserData();
			}
			return !isLogin.value;
		};

		return {
			userInfo,
			isLogin,
			numData,
			lastUpdateTime,
			getNumData,
			addShareLog,
			setToken,
			updateUserData,
			resetUserData,
			loginAfter,
			logout,
			getInfo,
			clearLogin,
		};
	},
	{
		persist: {
			enabled: true,
		},
	},
);

export default user;
